package com.five.controller;

import com.five.dto.CommentCreateDTO;
import com.five.dto.IdRequest;
import com.five.exception.BusinessException;
import com.five.pojo.Comment;
import com.five.result.Result;
import com.five.service.ICommentService;
import com.five.vo.CommentTreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private ICommentService commentService;

    /**
     * 创建评论/回复（支持无限层级）
     */
    @PostMapping("/create")
    public Result<Long> createComment(@RequestHeader("token") String token, @RequestBody CommentCreateDTO dto) {
        try {
            Long CommentId = commentService.createComment(token, dto);
            return Result.success(CommentId);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统繁忙，请稍后重试...");
        }
    }

    /**
     * 查询书籍的所有评论（含所有层级子回复，无分页）
     */
    @PostMapping("/tree")
    public Result<List<CommentTreeVO>> getCommentTree(@RequestBody IdRequest idRequest) {
        try {
            List<CommentTreeVO> tree = commentService.getCommentTree(idRequest.getNovelId());
            return Result.success(tree);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统繁忙，请稍后重试...");
        }
    }

    /*
     * 查询登陆人的所有评论
     * */
    @PostMapping("/listByLogininfo")
    public Result<List<Comment>> listByLogininfo(@RequestHeader("token") String token) {
        try {
            List<Comment> tree = commentService.listByLogininfo(token);
            return Result.success(tree);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统繁忙，请稍后重试...");
        }
    }

    /**
     * 删除自己的评论/回复
     */
    @PostMapping("/delete")
    public Result<Void> deleteComment(@RequestHeader("token") String token, Long commentId) {
        try {
            commentService.deleteComment(token, commentId);
            return Result.success("删除成功");
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统繁忙，请稍后重试...");
        }
    }
}